#!/usr/bin/python2.6

import Queue
import threading
import InitConfig as config
import xmlrpclib
import log_file
import logSendConfig
import commands
import rpcServer
import logging


a = config.Config()
ip = a.getCobblerIp()
cobbler_usr = a.getCobblerUsr()
cobbler_pwd = a.getCobblerPwd()
log_path = a.getLogPath()
server = xmlrpclib.Server("http://%s/cobbler_api"%(ip))
logging.basicConfig(filename = log_path, level = logging.DEBUG)

class listionExport:
    """
    listion import status with use thread
    @user pengfei guo
    """

    link = []
    queue = Queue.Queue(0)

    def __init__(self):
        # self.MyThread(self.queue).start()
        pass

    def addLink(self, pid):
        """
        add new pid to thread
        :param pid:
        :return:
        """
        self.queue.put(pid)
        self.MyThread(self.queue).start()

    class MyThread(threading.Thread):
        """
        thread
        """
        th_link = []
        th_queue = []

        def __init__(self, queue):
            self.th_queue = queue
            threading.Thread.__init__(self)

        def run(self):
            while True:
                if self.th_queue.qsize() > 0:
                    pid = self.th_queue.get()
                    # print "get pid is %s"%(pid)
                    m = False
                    while not m:
                        returnType = pidStatus(pid=pid[0])
                        # logging.warning('%s------%s'%(pid,returnType))
                        if returnType == "complete" :
                            # print "%sgame over\n"%(pid)
                            importName = pid[1][:pid[1].rfind(".")]
                            a,b = commands.getstatusoutput('umount /var/www/html/os/%s'%(importName))
                            if a ==0 or a =="0":
                                logging.warning('umount /var/www/html/os/%s success!'%(importName))
                                # log_file.writeTextLog("umount", content='umount /var/www/html/os/%s success!'%(importName))
                            else :
                                logging.warning('umount /var/www/html/os/%s error!'%(importName))

                            server ,token =rpcServer.getCobblerService()
                            server.remove_profile(importName,token)
                            logSendConfig.importStatus(taskId=pid[2],osName=pid[1],imp_type=2)
                            break
                        elif returnType =="running":
                            # print "%srunning....\n"%(pid)
                            logSendConfig.importStatus(taskId=pid[2],osName=pid[1],imp_type=1)
                        else:
                            logSendConfig.importStatus(taskId=pid[2],osName=pid[1],imp_type=3,content=returnType)
                            break
                else:
                    self.th_queue.join()

def pidStatus(pid):
    """
    query  thread status with pid
    :param pid:  thread id
    :return:  status ,if error ,return  all query message
    """
    pidstatus = server.get_task_status(pid)
    try:
        status = pidstatus[2]
    except :
        status = pidstatus
    finally:
        return status



    num = len(self.temp)
    index = random.randint(0, num - 1)
    return self.temp[index]



# a = listionExport()
# a.addLink(['2016-03-31_201713_import','CentOS-6.5-x86_64.iso'])